extends NodeState



var player: Player:
	get:
		return state_matchine.root as Player


func _on_process(_delta : float) -> void:
	pass


func _on_enter(_data: NodeStateData) -> void:
	player.velocity = Vector2.ZERO
	process_animation()


func _on_exit() -> void:
	pass


func find_teammate() -> Player:
	var bodies := player.teammate_detection_area.get_overlapping_bodies()
	var teammates := bodies.filter(
		func(body: Node2D):
			return body is Player and body != player and body.control_schema == player.control_schema
	)
	if teammates.size() == 0:
		return null

	teammates.sort_custom(
		func(p1: Player, p2: Player):
			return p1.position.distance_squared_to(player.position) < p2.position.distance_squared_to(player.position)
	)
	return teammates[0]



func pass_to_teammate(teammate: Player):
	if teammate:
		# 传球到队友时，需要目标位置是队友即将到达的位置
		player.ball.pass_to(teammate.position + teammate.velocity)
		return
	# 若没找到队友，则按照方向或者角色朝向传出球
	var direction := player.input_manager.movement_direction if player.input_manager.is_movement() else player.character_direction()
	player.ball.pass_to(player.ball.position + direction * player.speed)




func process_animation():
	player.animation_player.play(Player.ANIMATION_PASS)


func on_animation_finished():
	var teammate := find_teammate()
	if player.is_carrying_ball():
		pass_to_teammate(teammate)

	if player.input_manager.is_movement():
		transition_state(Player.STATE_RUN)
		return
	transition_state(Player.STATE_IDLE)
